<template>
  <ContentWrap>
    <el-menu
      :default-active="activeIndex"
      style="margin-bottom: 10px"
      mode="horizontal"
      @select="handleSelect"
    >
      <el-menu-item index="my">我的客户</el-menu-item>
      <el-menu-item index="sub">下属客户</el-menu-item>
    </el-menu>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="客户名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入手机"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="客户级别" prop="level">
        <el-select
          v-model="queryParams.level"
          clearable
          placeholder="请选择客户级别"
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CRM_CUSTOMER_LEVEL)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户状态" prop="industry">
        <el-select
          v-model="queryParams.industry"
          clearable
          placeholder="请选择客户状态"
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CRM_CUSTOMER_INDUSTRY)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="负责人" prop="ownUserName">
        <el-select
          v-model="queryParams.ownUserName"
          clearable
          placeholder="请选择负责人"
          class="!w-240px"
        >
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.nickname"
            :value="item.nickname"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="微信" prop="weixin">
        <el-input
          v-model="queryParams.weixin"
          placeholder="请输入微信"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="QQ" prop="qq">
        <el-input
          v-model="queryParams.qq"
          placeholder="请输入QQ"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="下次跟进" prop="nextDate">
        <el-date-picker
          v-model="queryParams.nextDate"
          type="date"
          placeholder="请选择跟进日期"
          @keyup.enter="handleQuery"
          value-format="YYYY-MM-DD"
          :shortcuts="shortcuts"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="负责人" prop="ownUserName">
        <el-input
          v-model="queryParams.ownUserName"
          placeholder="请输入负责人"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="跟进状态" prop="followStatus">
        <el-select
          v-model="queryParams.followStatus"
          placeholder="请选跟进状态"
          clearable
          class="!w-240px"
        >
          <el-option label="未跟进" value="1" />
          <el-option label="待跟进" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建日期" prop="createDate">
        <el-date-picker
          v-model="createDate"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="changeDate"
          value-format="YYYY-MM-DD"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="城市" prop="city">
        <el-cascader
          v-model="cityArr"
          :options="areaList"
          :props="props"
          filterable
          @change="handleChange"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['crm:customer:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button plain type="warning" @click="openUpload" v-hasPermi="['crm:customer:upload']">
          <Icon icon="ep:upload" class="mr-5px" /> 导入
        </el-button>
        <el-button plain type="warning" @click="handleExport" v-hasPermi="['crm:customer:export']">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          plain
          type="danger"
          @click="openMail"
          :disabled="isDisabled"
          v-hasPermi="['crm:customer:transfer']"
        >
          <Icon icon="ep:switch" class="mr-5px" /> 转移客户
        </el-button>
        <el-button
          plain
          type="danger"
          @click="openPublic"
          :disabled="isDisabled"
          v-hasPermi="['crm:customer:transfer']"
        >
          <Icon icon="ep:share" class="mr-5px" /> 公海客户
        </el-button>
        <el-dropdown trigger="click" class="ml-5px">
          <el-button plain type="success"> <Icon icon="ep:filter" /> 自定义列 </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item v-for="col in allColumns" :key="col.prop">
                <el-checkbox
                  v-model="visibleColumns"
                  :label="col.prop"
                  @change="saveColumnSettings"
                >
                  {{ col.label }}
                </el-checkbox>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      border
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleSelectionChange"
      @sort-change="handleSortChange"
    >
      <!-- 固定列 -->
      <el-table-column type="selection" width="40" />
      <el-table-column type="index" width="70" label="序号" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="70" />

      <!-- 动态列 -->
      <template v-for="col in displayColumns" :key="col.prop">
        <!-- 客户名称列（特殊处理） -->
        <el-table-column
          v-if="col.prop === 'name'"
          label="客户名称"
          align="center"
          prop="name"
          width="120"
        >
          <template #default="scope">
            <div @click="openDetail(scope.row.id)" style="color: #409eff; cursor: pointer">
              {{ scope.row.name }}
            </div>
            <div
              v-if="scope.row.tags.length > 0"
              style="display: flex; flex-wrap: wrap; justify-content: center"
            >
              <el-tag
                type="danger"
                round
                size="small"
                v-for="(tag, idx) in scope.row.tags"
                :key="idx"
              >
                {{ tag }}
              </el-tag>
            </div>
          </template>
        </el-table-column>

        <!-- 客户级别列（特殊处理） -->
        <el-table-column
          v-else-if="col.prop === 'level'"
          label="客户级别"
          align="center"
          prop="level"
          width="80"
        >
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.CRM_CUSTOMER_LEVEL" :value="scope.row.level" />
          </template>
        </el-table-column>

        <!-- 客户状态列（特殊处理） -->
        <el-table-column
          v-else-if="col.prop === 'industry'"
          label="客户状态"
          align="center"
          prop="industry"
          width="80"
        >
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.CRM_CUSTOMER_INDUSTRY" :value="scope.row.industry" />
          </template>
        </el-table-column>

        <!-- 时间列（特殊处理） -->
        <el-table-column
          v-else-if="['createTime', 'nextTime', 'followTime', 'collectTime'].includes(col.prop)"
          :sortable="col.sortable"
          :label="col.label"
          align="center"
          :prop="col.prop"
          :formatter="dateFormatter"
          width="180px"
        />

        <!-- 操作列（特殊处理） -->
        <el-table-column
          v-else-if="col.prop === 'action'"
          label="操作"
          align="center"
          fixed="right"
          width="160"
        >
          <template #default="scope">
            <el-button link type="primary" @click="openDetail(scope.row.id)">跟进</el-button>
            <!-- <el-button link type="primary" @click="openForm('update', scope.row.id)"
              v-hasPermi="['crm:customer:update']">编辑</el-button> -->
            <el-button
              link
              type="danger"
              @click="handleDelete(scope.row.id)"
              v-hasPermi="['crm:customer:delete']"
              >删除</el-button
            >
          </template>
        </el-table-column>

        <!-- 普通列 -->
        <el-table-column
          v-else
          :sortable="col.sortable"
          :label="col.label"
          align="center"
          :prop="col.prop"
          :width="col.width"
        />
      </template>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <CustomerForm ref="formRef" @success="getList" />
  <RecordForm ref="recordFormRef" @close-form="getList" />
  <UploadTemplate ref="UploadTemplateRef" @success="getList" />
  <TransferTemplateForm ref="TransferTemplateFormRef" @success="getList" />
  <PublicTemplateForm ref="PublicTemplateFormRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { CustomerApi, CustomerVO } from '@/api/crm/crmcustomer'
import CustomerForm from './CustomerForm.vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import RecordForm from '@/views/crm/crmrecord/RecordForm.vue'
import UploadTemplate from '@/views/components/upload/UploadTemplate.vue'
import TransferTemplateForm from '@/views/components/transfer/TransferTemplateForm.vue'
import PublicTemplateForm from '@/views/components/transfer/PublicTemplateForm.vue'
import { useLocalStorage } from '@vueuse/core'
import * as UserApi from '@/api/system/user'
import * as AreaApi from '@/api/system/area'
import { getProvinceCityData } from '@/utils/tree'
const route = useRoute() // 路由
/** 客户 列表 */
defineOptions({ name: 'CrmCustomer' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const props = {
  value: 'id',
  label: 'name'
}
const loading = ref(true) // 列表的加载中
const list = ref<CustomerVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const createDate = ref<string[]>([])
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  mobile: undefined,
  telephone: undefined,
  dealStatus: undefined,
  level: undefined,
  industry: undefined,
  tags: undefined,
  source: undefined,
  remark: undefined,
  userId: undefined,
  province: undefined,
  city: undefined,
  area: undefined,
  weixin: undefined,
  qq: undefined,
  sortColum: '',
  sortOrder: '',
  nextDate: '',
  ownUserName: '',
  followStatus: '',
  relation: 'my',
  startCreateDate: undefined,
  endCreateDate: undefined
})
const userList = ref([])
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const activeIndex = ref('my')
const selectCustomers = ref([])
const isDisabled = ref(true)
const cityArr = ref([])
const areaList = ref([])
const shortcuts = [
  {
    text: '今日',
    value: new Date()
  },
  {
    text: '明日',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() + 3600 * 1000 * 24)
      return date
    }
  }
]

// 所有列配置
const allColumns = ref([
  { prop: 'name', label: '客户名称', width: 120 },
  { prop: 'mobile', label: '手机', width: 150 },
  { prop: 'ownUserName', label: '负责人', width: 120 },
  { prop: 'level', label: '客户级别', width: 80 },
  { prop: 'industry', label: '客户状态', width: 80 },
  { prop: 'createTime', label: '创建时间', width: 180, sortable: true },
  { prop: 'nextTime', label: '下次跟进', width: 180, sortable: true },
  { prop: 'remark', label: '跟进备注', width: 200 },
  { prop: 'cityName', label: '城市', width: 200 },
  { prop: 'followTime', label: '最后跟进', width: 180, sortable: true },
  { prop: 'collectTime', label: '领取时间', width: 180, sortable: true },
  { prop: 'weixin', label: '微信', width: 120 },
  { prop: 'qq', label: 'QQ', width: 120 },
  { prop: 'action', label: '操作', width: 160 }
])
// 默认显示的列（ID和选择列总是显示）
const defaultVisibleColumns = [
  'name',
  'mobile',
  'ownUserName',
  'industry',
  'createTime',
  'nextTime',
  'remark',
  'action'
]

// 使用本地存储保存列设置
const visibleColumns = useLocalStorage('crm-customer-columns', defaultVisibleColumns)

// 计算实际显示的列（排除固定列）
const displayColumns = computed(() => {
  return allColumns.value.filter((col) => visibleColumns.value.includes(col.prop))
})

// 保存列设置到本地存储
const saveColumnSettings = () => {
  localStorage.setItem('crm-customer-columns', JSON.stringify(visibleColumns.value))
}
//获取用户列表
const getuserList = async () => {
  userList.value = await UserApi.getUserListAllSimple({})
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await CustomerApi.getCustomerPage(queryParams)
    list.value = data.list
    list.value.map((value) => {
      if (value.tags != '') {
        value.tags = value.tags.split(',')
      }
    })
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const handleSelectionChange = (val) => {
  if (val.length > 0) {
    isDisabled.value = false
  }
  selectCustomers.value = val
}
const handleSortChange = ({ prop, order }) => {
  queryParams.sortColum = prop
  queryParams.sortOrder = order
  getList()
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}
const handleChange = (value) => {
  if (value) {
    queryParams.province = value[0]
    queryParams.city = value[1]
    queryParams.area = value[2]
  }
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.province = ''
  queryParams.city = ''
  queryParams.area = ''
  cityArr.value = []
  handleQuery()
}

const handleSelect = (key) => {
  queryParams.relation = key
  getList()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

const recordFormRef = ref()
const openDetail = (id?: number) => {
  recordFormRef.value.open('', id)
}

const handleOpen = async (id: number) => {
  try {
    // 删除的二次确认
    await message.confirm('确定把客户放入公海')
    // 发起删除
    await CustomerApi.openCustomer(id)
    message.success('放入成功')
    // 刷新列表
    await getList()
  } catch {}
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await CustomerApi.deleteCustomer(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await CustomerApi.exportCustomer(queryParams)
    download.excel(data, '客户.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const UploadTemplateRef = ref()
const openUpload = () => {
  UploadTemplateRef.value.open(selectCustomers.value, true)
}

const TransferTemplateFormRef = ref()
const PublicTemplateFormRef = ref()
const openMail = () => {
  TransferTemplateFormRef.value.open(selectCustomers.value, true)
}
const openPublic = () => {
  PublicTemplateFormRef.value.open(selectCustomers.value, true)
}
const changeDate = (value) => {
  if (value) {
    queryParams.startCreateDate = value[0]
    queryParams.endCreateDate = value[1]
  } else {
    queryParams.startCreateDate = undefined
    queryParams.endCreateDate = undefined
  }
}

/** 初始化 **/
onMounted(async () => {
  const savedColumns = localStorage.getItem('crm-customer-columns')
  if (savedColumns) {
    visibleColumns.value = JSON.parse(savedColumns)
  }

  console.log(route.query.followType, 'route')
  if (route.query.followType) {
    queryParams.followStatus = route.query.followType
  }
  const cityData = await AreaApi.getAreaTree()
  areaList.value = getProvinceCityData(cityData)
  getuserList()
  getList()
})
</script>
